package com.intelligent.system.common.controller;

import com.intelligent.system.common.response.ResultDO;
import com.intelligent.system.common.sse.SseEmitterManager;
import com.intelligent.system.common.sse.SseMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@Api(tags = "SSE事件推送")
@RestController
@RequestMapping("/api/sse")
@RequiredArgsConstructor
public class SseController {
    private final SseEmitterManager sseEmitterManager;

    @ApiOperation("建立SSE连接")
    @GetMapping("/connect/{clientId}")
    public SseEmitter connect(
            @ApiParam("客户端ID") @PathVariable String clientId) {
        return sseEmitterManager.createConnection(clientId);
    }

    @ApiOperation("发送消息给指定客户端")
    @PostMapping("/send/{clientId}")
    public ResultDO<Void> sendMessage(
            @ApiParam("客户端ID") @PathVariable String clientId,
            @ApiParam("消息内容") @RequestBody SseMessage message) {
        sseEmitterManager.sendMessage(clientId, message);
        return ResultDO.success(null);
    }

    @ApiOperation("发送消息给所有客户端")
    @PostMapping("/send/all")
    public ResultDO<Void> sendMessageToAll(@ApiParam("消息内容") @RequestBody SseMessage message) {
        sseEmitterManager.sendMessageToAll(message);
        return ResultDO.success(null);
    }

    @ApiOperation("关闭指定客户端的连接")
    @PostMapping("/close/{clientId}")
    public ResultDO<Void> closeConnection(@ApiParam("客户端ID") @PathVariable String clientId) {
        sseEmitterManager.closeConnection(clientId);
        return ResultDO.success(null);
    }

    @ApiOperation("关闭所有连接")
    @PostMapping("/close/all")
    public ResultDO<Void> closeAllConnections() {
        sseEmitterManager.closeAllConnections();
        return ResultDO.success(null);
    }

    @ApiOperation("获取在线客户端数量")
    @GetMapping("/online/count")
    public ResultDO<Integer> getOnlineCount() {
        return ResultDO.success(sseEmitterManager.getOnlineCount());
    }
} 